package com.yuma.cas;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

class DataOne{
    // 加上volatile不能解决线程安全，只能保证线程每次都是主内存的内存
//    private volatile Integer number = 0;
    private AtomicInteger number = new AtomicInteger(0);

    public Integer incr(){
//        return ++number;  // ++ 线程不安全
       return number.incrementAndGet();
    }
}

public class VolatileAtomicDemo {

    public static void main(String[] args) throws InterruptedException {

        DataOne dataOne = new DataOne();
        CountDownLatch countDownLatch = new CountDownLatch(1000);

        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                System.out.println(dataOne.incr());
                countDownLatch.countDown();
            }).start();
        }

        countDownLatch.await();
        System.out.println("over");
    }
}